/**
 * @author kent
 * @date 16/6/17.
 */
(function () {

    // ----------------页面元素相关操作封装------------------

    var ElementRef = (function () {

        /**
         * 定义待返回对象构造函数
         * @param scope
         * @param searchForm
         * @param table
         * @param editor
         * @constructor
         */
        function Ref(scope, table, editor, searchForm) {
            this._table = table;
            this._scope = scope;
            this._editor = editor;
            this._searchForm = searchForm;
        }

        Ref.prototype = {
            constructor: Ref,

            init(initBefore,initAfter){

                if (initBefore && typeof initBefore == 'function'){
                    initBefore.call();
                }

                initScope(this);
                initSearchForm(this);
                initEditor(this);
                initTable(this);

                if (initAfter && typeof initAfter == 'function'){
                    initAfter.call();
                }

                return this;
            },

            insert(obj){
                this.vm.data = obj || {};
                this.openEditor();
            },
            exportExcel(url){
                var self=this;
                window.open(url+"?queryCondition=" + archer.utils.mergeParams({data: this.vm.sort}, self.$searchForm));
            },
            loadTableData(url, params, callBack, callBackContext){
                var self = this;
                httpGet({
                    url: url,
                    params: {queryCondition: archer.utils.mergeParams(params, self.$searchForm)},
                    selfCallBackContext: self,
                    customCallBack: callBack,
                    customCallBackContext: callBackContext,
                    selfSuccessCallBack(data) {
                        if (archer.utils.isEmpty(data.resultData)) {
                            params.success([]);
                        } else {
                            if (archer.utils.isEmpty(data.resultData.total)) {
                                // 非分页查询结果
                                params.success(data.resultData);
                            } else {
                                // 分页查询结果
                                params.success({
                                    total: data.resultData.total,
                                    rows: data.resultData.rows
                                });
                            }
                        }
                    },
                    selfErrorCallBack(data) {
                        // 通知table加载数据失败
                        params.error({status: data.resultCode});
                    }
                });
            },
            reloadTableData(){
                if (this.$table) {
                    this.$table.bootstrapTable('refresh');
                }
            },
            store(url, afterStore, callBackContext){
                var self = this;
                httpPost({
                    url: url,
                    params: self.vm.data,
                    selfCallBackContext: self,
                    customCallBack: afterStore,
                    customCallBackContext: callBackContext,
                    selfSuccessCallBack(data){
                        if (!archer.utils.isEmpty(data.resultData) && !archer.utils.isEmpty(data.resultData.id)) {
                            this.vm.query.id = data.resultData.id;
                            this.vm.data = data.resultData;
                        }

                        this.reloadTableData();
                        this.hideEditor();
                    }
                });
            },
            update(obj){
                this.vm.data = obj || {};
                this.openEditor();
            },
            remove(url, params, callBack, callBackContext){
                var self = this;
                archer.confirm(function () {
                    httpPost({
                        url: url,
                        params: params,
                        selfCallBackContext: self,
                        customCallBack: callBack,
                        customCallBackContext: callBackContext,
                        selfSuccessCallBack(data){
                            this.reloadTableData();
                        }
                    })
                });
            },
            loadFormData(url, params, callBack, callBackContext){
                var self = this;
                httpGet({
                    url: url,
                    params: params,
                    selfCallBackContext: self,
                    customCallBack: callBack,
                    customCallBackContext: callBackContext,
                    selfSuccessCallBack(data){
                        this.vm.data = data.resultData;
                    }
                })
            },
            openEditor(){
                this.$editor.modal({show: true});
            },
            hideEditor(){
                this.$editor.modal('hide');
            },
            id(){
                return this.vm.query.id;
            },
            getSelections(col){
                return getSelections(col, this);
            },
            get(url, params, success, context){
                httpGet({
                    url: url,
                    params: params,
                    customCallBack: success,
                    customCallBackContext: context
                });
            },
            post(url, params, success, context){
                httpPost({
                    url: url,
                    params: params,
                    customCallBack: success,
                    customCallBackContext: context
                });
            }
        };

        //-------------------私有方法----------------------
        function initScope(obj) {
            if (!obj._scope) {
                return;
            }

            obj.vm = new Vue({
                data: {
                    // 存放编辑对象
                    data: {},
                    // 存放查询数据
                    query: purl().param(),
                    // 存放列表排序,格式为{sortName:xxx,sortOrder:xxx}
                    sort: {},
                    // 存放其他数据
                    other: {},
                    // id初始时从url获取,表单保存后重新赋值
                    //id: archer.http.getQueryString('id')  移到query对象中
                },

                el: obj._scope
            });
        }

        function initTable(obj) {
            if (!obj._table) {
                return;
            }

            var self = obj;
            //添加onSort监听,记录下排序字段
            obj.$table = $(obj._table).bootstrapTable({
                onSort: function (name, order) {
                    self.vm.sort = {
                        sortName: name,
                        sortOrder: order
                    };
                }
            });
        }

        function initEditor(obj) {
            if (!obj._editor) {
                return;
            }
            obj.$editor = $(obj._editor).modal({show: false});
        }

        function initSearchForm(obj) {
            obj.$searchForm = $(obj._searchForm);
        }

        function getSelections(col, context) {
            var selected = context.$table.bootstrapTable('getSelections');

            if (archer.utils.isEmpty(selected)) {
                return [];
            }

            if (archer.utils.isEmpty(col)) {
                return selected;
            }

            var param = [];
            for (var i = 0; i < selected.length; i++) {
                param.push(selected[i][col]);
            }
            return param;
        }

        /**
         * 公共get请求
         * @param url
         * @param params
         * @param selfSuccessCallBack   成功回调
         * @param selfCallBackContext   成功回调上下文（成功和失败回调的上下文是一致的）
         * @param selfErrorCallBack     失败回调
         * @param customCallBack        调用者（此js的引用者）成功回调
         * @param customCallBackContext 回调上下文
         */
        function httpGet({
            url, params,
            selfSuccessCallBack, selfCallBackContext, selfErrorCallBack,
            customCallBack, customCallBackContext
            }) {
            archer.http.get(url, params, function (data) {
                httpCallBack({
                    data: data,
                    selfCallBackContext: selfCallBackContext,
                    selfSuccessCallBack: selfSuccessCallBack,
                    selfErrorCallBack: selfErrorCallBack,
                    customCallBack: customCallBack,
                    customCallBackContext: customCallBackContext
                })
            });
        }

        /**
         * post请求
         * @param url
         * @param params
         * @param selfSuccessCallBack
         * @param selfCallBackContext
         * @param selfErrorCallBack
         * @param customCallBack
         * @param customCallBackContext
         */
        function httpPost({
            url, params,
            selfSuccessCallBack, selfCallBackContext, selfErrorCallBack,
            customCallBack, customCallBackContext
            }) {
            archer.http.post(url, params, function (data) {
                httpCallBack({
                    data: data,
                    selfCallBackContext: selfCallBackContext,
                    selfSuccessCallBack: selfSuccessCallBack,
                    selfErrorCallBack: selfErrorCallBack,
                    customCallBack: customCallBack,
                    customCallBackContext: customCallBackContext
                })
            });
        }

        /**
         * http请求回调
         * @param data
         * @param selfSuccessCallBack
         * @param selfCallBackContext
         * @param selfErrorCallBack
         * @param customCallBack
         * @param customCallBackContext
         */
        function httpCallBack({
            data,
            selfSuccessCallBack, selfCallBackContext, selfErrorCallBack,
            customCallBack, customCallBackContext
            }) {
            if (archer.utils.isSuccess(data)) {
                invokeCallBack(selfSuccessCallBack, data, selfCallBackContext);
                invokeCallBack(customCallBack, data, customCallBackContext);
                successTip(data.resultMsg);
            } else {
                invokeCallBack(selfErrorCallBack, data, selfCallBackContext);
                errorTip(data.resultMsg);
            }
        }

        /**
         * 执行回调
         * @param callBack
         * @param param
         * @param context
         */
        function invokeCallBack(callBack, param, context) {
            if (!callBack || typeof callBack != 'function') {
                return;
            }

            callBack.call(context ? context : window, param);
        }

        function errorTip(errMsg) {
            archer.toast.error({msg: errMsg});
        }

        function successTip(successMsg) {
            archer.toast.success({msg: successMsg});
        }

        //返回构造方法
        return Ref;
    })();

    // ---------------对外提供的crud方法-------------------

    window._crud = window._crud || {
            // 初始化
            createCrud({scope='', table='', editor='', searchForm=''}) {
                return new ElementRef(scope, table, editor, searchForm);
            }
        };
})();
